package com.p2l.letterblocks;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;

public class ActivityLogin extends Activity {
	private InsertLoginTask iTask;
	private SyncronizeTask sTask;
	
	private SharedPreferences preferences;
	private RelativeLayout company;
	private LinearLayout background;
	private EditText username, password;
	private TextView create;
	private ProgressBar bar;
	private CheckBox remember;
	private Context context;
	private Button login;
	
	private long time;
	private int mode;
	
	public int userId;
	
	@Override
	public void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		
		final WindowManager.LayoutParams brightness = getWindow().getAttributes();
		brightness.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        getWindow().setAttributes(brightness);
		
		context = this;
		preferences = getSharedPreferences("LetterBlocks", Activity.MODE_PRIVATE);
		String user = preferences.getString("username", null);
		String pass = preferences.getString("password", null);
		Boolean bool = getIntent().getBooleanExtra("login", false);
		time = Calendar.getInstance().getTimeInMillis();
		
		if (user != null && pass != null && !bool) {
			setContentView(R.layout.splash);
			company = (RelativeLayout) findViewById(R.id.company);
			userId = -1;
			mode = 1;
			
			Database db = new Database(context);
			SQLiteDatabase sqlite = db.getWritableDatabase();
			String select = "SELECT *";
    		String where = " WHERE username='" + user + "' AND password='" + pass + "'";
			Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_USERS, "", where);
			if (cursor.moveToFirst()) {
				userId = cursor.getInt(1);
				
				if (userId != -1) {
					time = Calendar.getInstance().getTimeInMillis();
					db.close();
					iTask = new InsertLoginTask();
					iTask.execute(userId);
					sTask = new SyncronizeTask();
					sTask.execute(userId);
				}
			} else {
				prepareLoginScreen();
			}
			db.close();
		} else {
			prepareLoginScreen();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (mode == 0) {
			if (background.getBackground() != null)
				background.getBackground().setCallback(null);
			if (remember.getBackground() != null)
				remember.getBackground().setCallback(null);
			if (username.getBackground() != null)
				username.getBackground().setCallback(null);
			if (password.getBackground() != null)
				password.getBackground().setCallback(null);
			if (login.getBackground() != null)
				login.getBackground().setCallback(null);
		}
		
		if (iTask != null) {
			if (iTask.getStatus() == Status.RUNNING) {
				iTask.cancel(true);
				iTask = null;
			}
		}
		
		if (sTask != null) {
			if (sTask.getStatus() == Status.RUNNING) {
				sTask.cancel(true);
				sTask = null;
			}
		}
		
		preferences = null;
		background = null;
		username = null;
		password = null;
		remember = null;
		context = null;
		company = null;
		create = null;
		login = null;
		bar = null;
		
		System.gc();
	}
	
	private void prepareLoginScreen() {
		setContentView(R.layout.login);
		mode = 0;
		
		background = (LinearLayout) findViewById(R.id.login_background);
		remember = (CheckBox) findViewById(R.id.chkRemember);
		username = (EditText) findViewById(R.id.txtUsername);
		password = (EditText) findViewById(R.id.txtPassword);
		bar = (ProgressBar) findViewById(R.id.pbrLogin);
		
		create = (TextView) findViewById(R.id.lblCreate);
		create.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// start 'create user' activity
				Intent intent = new Intent(v.getContext(), ActivityCreateUser.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
			}
		});
		
		login = (Button) findViewById(R.id.btnLogin);
		login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// if username is not typed
				if (username.getText().length() < 1) {
					Toast.makeText(v.getContext(), getResources().getString(R.string.error_no_username), Toast.LENGTH_LONG).show();
				// if password is not type
				} else if (password.getText().length() < 1) {
					Toast.makeText(v.getContext(), getResources().getString(R.string.error_no_password), Toast.LENGTH_LONG).show();
				// login
				} else {
		    		bar.setVisibility(View.VISIBLE);
		    		login.setVisibility(View.GONE);
		    		
		    		Database db = new Database(context);
					SQLiteDatabase sqlite = db.getWritableDatabase();
		    		String select = "SELECT *";
		    		String where = " WHERE username='" + username.getText().toString() + "' AND password='" + password.getText().toString() + "'";
					Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_USERS, "", where);
					if (cursor.moveToFirst()) {
						userId = cursor.getInt(1);
						
						if (userId != -1) {
							setContentView(R.layout.splash);
							company = (RelativeLayout) findViewById(R.id.company);
							time = Calendar.getInstance().getTimeInMillis();
							
							// remember username and password
							if (remember.isChecked()) {
								Editor editor = preferences.edit();
								editor.putString("username", username.getText().toString());
								editor.putString("password", password.getText().toString());
								editor.commit();
								editor = null;
							// don't remember username and password
							} else {
								Editor editor = preferences.edit();
								editor.remove("username");
								editor.remove("password");
								editor.commit();
								editor = null;
							}
						}
						
						iTask = new InsertLoginTask();
						iTask.execute(userId);
						sTask = new SyncronizeTask();
						sTask.execute(userId);
					} else {
						new LoginTask().execute();
					}
					select = null;
					where = null;
					cursor = null;
					db.close();
					db = null;
					sqlite = null;
				}
			}
		});
	}
	
	private class LoginTask extends AsyncTask<Void, Void, Boolean> {
		private Activity a;
		
    	@Override
		protected Boolean doInBackground(Void... params) {
			try {
				InputStream in;
				String dates = preferences.getString("dates", null);
				
				if (dates != null) {
					in = Server.open(Server.URL_OFFLINE_LOGINS + "?dates=" + dates.replaceAll(" ", "%20"));
					Editor editor = preferences.edit();
					editor.remove("dates");
					editor.commit();
					editor = null;
					in.close();
				}

				int version = 0;
				try {
					PackageManager manager = getPackageManager();
					version = manager.getPackageInfo(getPackageName(), 0).versionCode;
				} catch (Exception e) { }
				
				in = Server.open(Server.URL_LOGIN + "?username=" + username.getText().toString() + "&password=" + password.getText().toString() + "&version=" + version);
				XmlPullParser parser = Server.toXmlParser(in);
				userId = XmlParser.login(parser);
				in.close();
				in = null;
				
				if (userId != -1) {
					a = (Activity) context;
					a.runOnUiThread(new Runnable() {
    					@Override
    					public void run() {
    						setContentView(R.layout.splash);
							company = (RelativeLayout) findViewById(R.id.company);
    					}
					});
					
					time = Calendar.getInstance().getTimeInMillis();
					
					// remember username and password
					if (remember.isChecked()) {
						Editor editor = preferences.edit();
						editor.putString("username", username.getText().toString());
						editor.putString("password", password.getText().toString());
						editor.commit();
						editor = null;
					// don't remember username and password
					} else {
						Editor editor = preferences.edit();
						editor.remove("username");
						editor.remove("password");
						editor.commit();
						editor = null;
					}
					
					Database db = new Database(context);
					SQLiteDatabase sqlite = db.getWritableDatabase();
					String select = "SELECT *";
					String where = " WHERE username='" + username.getText().toString() + "' AND password='" + password.getText().toString() + "'";
					Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_USERS, "", where);
					if (cursor.getCount() == 0) {
						String[] values = { "" + userId, username.getText().toString(), password.getText().toString(), null };
						long result = db.insert(sqlite, Database.TABLE_NAME_USERS, Database.COLUMS_USERS, values);
						values = null;
					}
					db.close();
					cursor = null;
					db = null;
					sqlite = null;

		    		//iTask = new InsertLoginTask();
		    		//iTask.execute(userId);
		    		sTask = new SyncronizeTask();
		    		sTask.execute(userId);
				// if log in unsuccessful
				} else {
		    		runOnUiThread(new Runnable() {
						@Override
						public void run() {
				    		Toast.makeText(context, getResources().getString(R.string.error_login_failed), Toast.LENGTH_LONG).show();
						}
		    		});
					return false;
				}
				parser = null;
				dates = null;
			} catch (IOException e) {
				Log.e("LetterBlocks", e.toString());
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
			    		Toast.makeText(context, getResources().getString(R.string.error_no_server_connection), Toast.LENGTH_LONG).show();
					}
	    		});
				return false;
			} catch (XmlPullParserException e) {
				Log.e("LetterBlocks", e.toString());
				return false;
			}
			
			return true;
		}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (success) {
	    		setContentView(R.layout.splash);
				company = (RelativeLayout) findViewById(R.id.company);
	    	} else {
	    		login.setVisibility(View.VISIBLE);
	    		bar.setVisibility(View.GONE);
	    	}
	    	a = null;
	    	this.cancel(true);
	    }
	}
	
	private class InsertLoginTask extends AsyncTask<Integer, Void, Boolean> {
		private Database db;
		private SQLiteDatabase sqlite;
		
		private int userId;
		
    	@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				db = new Database(context);
				sqlite = db.getWritableDatabase();
				
				userId = params[0];
				
				// log login data
				int version = 0;
				try {
					PackageManager manager = getPackageManager();
					version = manager.getPackageInfo(getPackageName(), 0).versionCode;
				} catch (Exception e) { }
				
				String sql = Server.URL_INSERT_LOGIN + "?userId=" + userId + "&version=" + version;
				InputStream in = Server.open(sql);
				XmlPullParser parser = Server.toXmlParser(in);
				ArrayList<Login> logins = XmlParser.getLogins(parser);
				
				if (logins.size() != 0) {
					String select = "SELECT *";
		    		String where = " WHERE userId='" + userId + "'";

					Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_LOGINS, "", where);
					ArrayList<Login> saved_logins = db.getLogins(cursor);
					for (int i = 0; i < saved_logins.size(); i++) {
						sql = Server.URL_INSERT_LOGIN + "?userId=" + userId + "&date=" + saved_logins.get(i).getDate().replace(" ", "%20") + "&version=" + version;
						in = Server.open(sql);
						parser = Server.toXmlParser(in);
						ArrayList<Login> result = XmlParser.getLogins(parser);
						
						if (result.size() == 1) {
							where = "id='" + saved_logins.get(i).getId() + "'";
							if (!sqlite.isOpen())
								sqlite = db.getWritableDatabase();
							int res = db.delete(sqlite, Database.TABLE_NAME_LOGINS, where);
						}
					}
				}
				in.close();
				in = null;
			} catch (IOException e) {
				Log.e("LetterBlocks", e.toString());
				return false;
			} catch (XmlPullParserException e) {
				Log.e("LetterBlocks", e.toString());
				return false;
			}
			return true;
		}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (!success) {
	    		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+01:00"));
				int year = c.get(Calendar.YEAR);
				int month = c.get(Calendar.MONTH);
				int day = c.get(Calendar.DAY_OF_MONTH);
				int hour = c.get(Calendar.HOUR_OF_DAY);
				int minute = c.get(Calendar.MINUTE);
				int second = c.get(Calendar.SECOND);
				String date = year + "-" + (month < 10 ? "0" : "") + month + "-" + (day < 10 ? "0" : "") + day + " " + (hour < 10 ? "0" : "") + hour + ":" + (minute < 10 ? "0" : "") + minute + ":" + (second < 10 ? "0" : "") + second;

				int version = 0;
				try {
					PackageManager manager = getPackageManager();
					version = manager.getPackageInfo(getPackageName(), 0).versionCode;
				} catch (Exception e) { }
				
				String[] values = { "" + userId, date, "" + version };
				if (!sqlite.isOpen())
					sqlite = db.getWritableDatabase();
				long result = db.insert(sqlite, Database.TABLE_NAME_LOGINS, Database.COLUMS_LOGINS, values);
	    	}

	    	db.close();
			db = null;
			sqlite = null;
	    	this.cancel(true);
	    }
	}
	
	private class SyncronizeTask extends AsyncTask<Integer, Void, Boolean> {
		private Activity a;
		private Database db;
		private SQLiteDatabase sqlite;
		
    	@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				db = new Database(context);
				sqlite = db.getWritableDatabase();
				a = (Activity) context;
				
				// syncronizing
				syncChapterTransactions();
				syncChapters();
				syncItems();
				syncLevelsCompleted();
				
				InputStream in = Server.open(Server.URL_VERSION);
				XmlPullParser parser = Server.toXmlParser(in);
				parser.next();
				int version = XmlParser.getInt(parser, "Version");
				in.close();
				
				PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
				
				if (info.versionCode < version) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							DialogUpdate update = new DialogUpdate(context);
							update.show();
						}
		    		});
				} else {
					long end = Calendar.getInstance().getTimeInMillis();
					long elapsed = end - time;
					
					if (!isCancelled()) {
						try {
							if (elapsed < 2500) {
								Thread.sleep(2500 - elapsed);
							}
							a.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									company.setVisibility(View.INVISIBLE);
								}
							});
							Thread.sleep(2500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						
						// start main activity
						Intent intent = new Intent(context, ActivityMain.class);
						intent.putExtra("userId", userId);
						intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
						startActivity(intent);
						finish();
					} else {
						Log.d("LetterBlocks", "has been cancelled");
					}
				}
			} catch (IOException e) {
				Log.e("LetterBlocks", e.toString());
				Log.d("LetterBlocks", "No internet, skipping syncronization");
				
				long end = Calendar.getInstance().getTimeInMillis();
				long elapsed = end - time;
				try {
					if (elapsed < 2500) {
						Thread.sleep(2500 - elapsed);
					}
					a.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							company.setVisibility(View.INVISIBLE);
						}
					});
					Thread.sleep(2500);
				} catch (InterruptedException ie) {
					e.printStackTrace();
				}
				
				if (!isCancelled()) {
					Intent intent = new Intent(context, ActivityMain.class);
					intent.putExtra("userId", userId);
					intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
					startActivity(intent);
					finish();
				} else {
					Log.d("LetterBlocks", "has been cancelled");
				}
			} catch (XmlPullParserException e) {
				Log.e("LetterBlocks", e.toString());
			} catch (NameNotFoundException e) {
				Log.e("LetterBlocks", e.toString());
			} catch (NullPointerException e) {
				Log.e("LetterBlocks", e.toString());
			}
			return true;
		}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	this.cancel(true);
	    	db.close();
			db = null;
			sqlite = null;
	    }
	    
	    private void syncChapterTransactions() throws IOException, XmlPullParserException {
	    	InputStream in = Server.open(Server.URL_CHAPTER_TRANSACTIONS + "?userId=" + userId);
			XmlPullParser parser = Server.toXmlParser(in);
			ArrayList<ChapterTransaction> server_chapter_transactions = XmlParser.getChapterTransactions(parser);
			in.close();
			
			String select = "SELECT *";
			String where = " WHERE userId='" + userId + "'";
			Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_CHAPTER_TRANSACTIONS, "", where);
			ArrayList<ChapterTransaction> sqlite_chapter_transactions = db.getChapterTransactions(cursor);
			
			if (server_chapter_transactions.size() > sqlite_chapter_transactions.size()) {
				for (ChapterTransaction c : server_chapter_transactions) {
					int i = 0;
					boolean found = false;
					
					while (!found & i < sqlite_chapter_transactions.size()) {
						if (c.getId() == sqlite_chapter_transactions.get(i).getId())
							found = true;
						else
							i++;
					}
					
					if (!found) {
						String[] values = { "" + c.getId(), "" + c.getChapterId(), "" + c.getUserId(), "" + c.getPrice() };
						long result = db.insert(sqlite, Database.TABLE_NAME_CHAPTER_TRANSACTIONS, Database.COLUMS_CHAPTER_TRANSACTIONS, values);
					}
				}
			}
	    }
	    
	    private void syncChapters() throws IOException, XmlPullParserException {
			InputStream in = Server.open(Server.URL_USER_CHAPTERS + "?userId=" + userId);
			XmlPullParser parser = Server.toXmlParser(in);
			ArrayList<Chapter> server_chapters = XmlParser.getChapters(parser);
			in.close();
			
			String select = "SELECT TB_chapters.chapterId, TB_chapters.name, TB_chapters.price, TB_chapters.en, TB_chapters.es, TB_chapters.de, TB_chapters.dk";
			String join = " LEFT JOIN TB_chapter_transactions ON TB_chapters.chapterId = TB_chapter_transactions.chapterId";
			String where = " WHERE TB_chapters.price='0' OR TB_chapter_transactions.userId='" + userId + "'";
			Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_CHAPTERS, join, where);
			ArrayList<Chapter> sqlite_chapters = db.getChapters(cursor);
			
			if (server_chapters.size() > sqlite_chapters.size()) {
				for (Chapter c : server_chapters) {
					int i = 0;
					boolean found = false;
					
					while (!found & i < sqlite_chapters.size()) {
						if (c.getId() == sqlite_chapters.get(i).getId())
							found = true;
						else
							i++;
					}
					
					if (!found) {
						String[] values = { "" + c.getId(), c.getName(), "" + c.getPrice(), c.getDescription()[0], c.getDescription()[1], c.getDescription()[2], c.getDescription()[3] };
						long result = db.insert(sqlite, Database.TABLE_NAME_CHAPTERS, Database.COLUMS_CHAPTERS, values);
						syncLevels(c.getId());
					}
				}
			}
	    }
	    
	    private void syncLevels(int chapterId) throws IOException, XmlPullParserException {
	    	InputStream in = Server.open(Server.URL_LEVELS + "?chapterId=" + chapterId);
			XmlPullParser parser = Server.toXmlParser(in);
			ArrayList<Level> server_levels = XmlParser.getLevels(parser);
			in.close();
			
			String select = "SELECT *";
			String join = "";
			String where = " WHERE chapterId='" + chapterId + "'";
			Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_LEVELS, join, where);
			ArrayList<Level> sqlite_levels = db.getLevels(cursor);
			
			if (server_levels.size() > sqlite_levels.size()) {
				String levelIds = "";
				
				for (Level l : server_levels) {
					int i = 0;
					boolean found = false;
					
					while (!found && i < sqlite_levels.size()) {
						if (l.getId() == sqlite_levels.get(i).getId())
							found = true;
						else
							i++;
					}
					
					if (!found) {
						levelIds += (levelIds.length() == 0 ? "" : ",") + l.getId();
						String[] values = { "" + l.getId(), "" + l.getChapterId(), l.getBackground(), l.getLayer(), l.getFloor(), l.getDk(), l.getEn(), l.getDe(), l.getEs() };
						long result = db.insert(sqlite, Database.TABLE_NAME_LEVELS, Database.COLUMS_LEVELS, values);
					}
				}
				syncObjects(levelIds);
			}
	    }
	    
	    private void syncObjects(String levelIds) throws IOException, XmlPullParserException {
	    	InputStream in = Server.open(Server.URL_OBJECTS + "?levelIds=" + levelIds);
			XmlPullParser parser = Server.toXmlParser(in);
			ArrayList<P2LObject> server_objects = XmlParser.getObjects(parser);
			in.close();
			
			String select = "SELECT *";
			String join = "";
			String where = "";
			String[] ids = levelIds.split(",");
			for (String s : ids)
				where += (where.length() == 0 ? " WHERE " : " OR ") + "levelId='" + s + "'";
			Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_OBJECTS, join, where);
			ArrayList<P2LObject> sqlite_objects = db.getObjects(cursor);
			
			if (server_objects.size() > sqlite_objects.size()) {
				for (P2LObject o : server_objects) {
					int i = 0;
					boolean found = false;
					
					while (!found && i < sqlite_objects.size()) {
						if (o.getId() == sqlite_objects.get(i).getId())
							found = true;
						else
							i++;
					}
					
					if (!found) {
						String[] values = { "" + o.getId(), "" + o.getLevelId(), "" + o.getX(), "" + o.getY(), "" + o.getHeight(), "" + o.getWidth(), "" + o.getType(), o.getImage() };
						long result = db.insert(sqlite, Database.TABLE_NAME_OBJECTS, Database.COLUMS_OBJECTS, values);
					}
				}
			}
	    }
	    
	    private void syncItems() throws IOException, XmlPullParserException {
	    	InputStream in = Server.open(Server.URL_USER_ITEMS + "?userId=" + userId);
			XmlPullParser parser = Server.toXmlParser(in);
			ArrayList<Item> server_items = XmlParser.getItems(parser);
			in.close();
			
			String select = "SELECT TB_items.itemId, TB_items.name, TB_items.type, TB_items.price";
			String where = " WHERE TB_item_transactions.userId='" + userId + "'";
			String join = " LEFT JOIN TB_item_transactions ON TB_items.itemId = TB_item_transactions.itemId";
			Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_ITEMS, join, where);
			ArrayList<Item> sqlite_items = db.getItems(cursor);
			if (server_items.size() > sqlite_items.size()) {
				for (Item item : server_items) {
					int i = 0;
					boolean found = false;
					
					while (!found && i < sqlite_items.size()) {
						if (item.getId() == sqlite_items.get(i).getId())
							found = true;
						else
							i++;
					}
					
					if (!found) {
						String[] values = new String[] { "" + item.getId(), "" + userId, "" + item.getPrice() };
			    		long result = db.insert(sqlite, Database.TABLE_NAME_ITEM_TRANSACTIONS, Database.COLUMS_ITEM_TRANSACTIONS, values);
			    		//Log.d("LetterBlocks", item.getName() + " = " + result);
			    		values = new String[] { "" + item.getId(), item.getName(), "" + item.getType(), "" + item.getPrice() };
			    		result = db.insert(sqlite, Database.TABLE_NAME_ITEMS, Database.COLUMS_ITEMS, values);
			    		//Log.d("LetterBlocks", item.getName() + " = " + result);
					}
				}
			}
	    }
	    
	    private void syncLevelsCompleted() throws IOException, XmlPullParserException {
			String select = "SELECT *";
			String where = " WHERE userId='" + userId + "'";
			Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_LEVELS_COMPLETED, "", where);
			ArrayList<LevelCompleted> sqlite_level_completed = db.getLevelsCompleted(cursor);
			
			for (LevelCompleted l : sqlite_level_completed) {
				if (l.getLevelCompletedId() == -1) {
					String sql = Server.URL_INSERT_LEVEL_COMPLETED + "?levelId=" + l.getLevelId() + "&userId=" + userId + "&coin=" + (l.isCoin() ? "1" : "0");
					InputStream in = Server.open(sql);
					XmlPullParser parser = Server.toXmlParser(in);
					parser.next();
					int id = XmlParser.getInt(parser, "Id");
					in.close();
					
					where = "id='" + l.getId() + "'";
					String[] columns = { Database.COLUMS_LEVELS_COMPLETED[0] };
					String[] values = { "" + id }; 
					long result = db.update(sqlite, Database.TABLE_NAME_LEVELS_COMPLETED, columns, values, where);

					l.setLevelCompletedId(id);
				}
			}
			
	    	InputStream in = Server.open(Server.URL_LEVELS_COMPLETED + "?userId=" + userId);
			XmlPullParser parser = Server.toXmlParser(in);
			ArrayList<LevelCompleted> server_levels_completed = XmlParser.getLevelsCompleted(parser);
			in.close();
			
			if (server_levels_completed.size() > sqlite_level_completed.size()) {
				for (LevelCompleted l : server_levels_completed) {
					boolean found = false;
					int i = 0;
					
					while (!found && i < sqlite_level_completed.size()) {
						if (l.getLevelCompletedId() == sqlite_level_completed.get(i).getLevelCompletedId())
							found = true;
						else
							i++;
					}
					
					if (!found) {
						String[] values = { "" + l.getId(), "" + l.getLevelId(), "" + l.getUserId(), "" + l.getLanguage(), (l.isCoin() ? "1" : "0") };
						long result = db.insert(sqlite, Database.TABLE_NAME_LEVELS_COMPLETED, Database.COLUMS_LEVELS_COMPLETED, values);
					}
				}
			}
	    }
	}
}
